package com.rednote.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rednote.common.OssUtil;
import com.rednote.common.Result;
import com.rednote.common.UserContextHolder;
import com.rednote.entity.Comments;
import com.rednote.entity.Posts;
import com.rednote.entity.Users;
import com.rednote.entity.vo.AuthorVO;
import com.rednote.entity.vo.CommentVO;
import com.rednote.mapper.CommentsMapper;
import com.rednote.mapper.PostsMapper;
import com.rednote.mapper.UsersMapper;
import com.rednote.service.CommentsService;
import com.rednote.entity.dto.CommentDTO;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 帖子评论表(Comments)服务实现类
 *
 * @author yao suxuan
 * @since 2025-05-24 18:10:30
 */
@Service
public class CommentsServiceImpl extends ServiceImpl<CommentsMapper, Comments> implements CommentsService {
    @Autowired
    private UserLikesServiceImpl userLikesServiceImpl;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private CommentsMapper commentsMapper;
    @Autowired
    private PostsMapper postsMapper;
    @Resource
    private OssUtil ossUtil;

    public void createComment(Integer id, String content,List<MultipartFile> images, boolean isPostComment) throws JsonProcessingException {
        Comments comment = new Comments();
        // 验证图片文件（仅当有图片时进行验证）
        if (images != null && !images.isEmpty()) {
            for (MultipartFile image : images) {
                String imageContentType = image.getContentType();
                // 图片格式验证
                if (imageContentType == null || !imageContentType.startsWith("image/")) {
                    throw new RuntimeException("不支持的图片格式");
                }
                // 图片大小限制：10MB
                if (image.getSize() > 10 * 1024 * 1024) {
                    throw new RuntimeException("单个图片大小不能超过10MB");
                }
            }
            // 处理图片上传
            List<String> imageUrls = new ArrayList<>();
            if (images != null && !images.isEmpty()) {
                for (MultipartFile image : images) {
                    // 上传图片到 OSS images 目录
                    String imageUrl = ossUtil.uploadFile(image, "images");
                    imageUrls.add(imageUrl);
                }

                // 将图片 URL 列表转换为 JSON 字符串
                ObjectMapper mapper = new ObjectMapper();
                comment.setImageUrl(mapper.writeValueAsString(imageUrls));
            }
        }
            comment.setContent(content);
            Integer userId = UserContextHolder.getUserId();
            comment.setUserId(userId);//TODO: 获取当前登录用户ID
            comment.setCreatedAt(new Date());
            comment.setUpdatedAt(new Date());
            comment.setStatus(1);
            comment.setLikeCount(0);
            comment.setReplyCount(0);

            if (isPostComment) {
                // 对帖子评论
                comment.setPostId(id);
                comment.setRootId(0);
            } else {
                // 对评论回复
                Comments parentComment = commentsMapper.selectById(id);
                if (parentComment == null) throw new RuntimeException("被回复的评论不存在");

                comment.setPostId(parentComment.getPostId());
                comment.setParentId(parentComment.getCommentId());

                if (parentComment.getRootId() != null && parentComment.getRootId() != 0) {
                    comment.setRootId(parentComment.getRootId());
                } else {
                    comment.setRootId(parentComment.getCommentId());
                }
            }
            commentsMapper.insert(comment);
            // 增加帖子的回复数
            postsMapper.update(null,
                    new UpdateWrapper<Posts>()
                            .eq("post_id", comment.getPostId())
                            .setSql("comment_count = comment_count + 1")
            );
            //增加一级评论回复数
            if (!isPostComment) {
                commentsMapper.update(null,
                        new UpdateWrapper<Comments>()
                                .eq("comment_id", comment.getParentId())
                                .setSql("reply_count = reply_count + 1")
                );
            }


    }
    public void removeCommentById(Integer id){
        if(id == null) {
            throw new IllegalArgumentException("评论ID不能为空");
        }
        Comments comment= commentsMapper.selectById(id);
        if(comment == null) {
            throw new RuntimeException("评论不存在");
        }
        Integer userId= UserContextHolder.getUserId();
        if(userId == null || !userId.equals(comment.getUserId())) {
            throw new RuntimeException("无权限删除此评论");
        }
        int deletedCount = 1; // 先计入当前评论本身

        if (comment.getParentId() == null || comment.getParentId() == 0) {
            // 是一级评论，查找该评论下所有的二级评论数量
            List<Comments> subComments = commentsMapper.selectList(
                    new QueryWrapper<Comments>().eq("root_id", comment.getCommentId())
            );
            deletedCount += subComments.size();

            // 删除所有二级评论
            commentsMapper.delete(new QueryWrapper<Comments>().eq("root_id", comment.getCommentId()));
        }
        // 删除当前评论
        commentsMapper.deleteById(id);
        // 更新帖子的评论数
        postsMapper.update(null,
                new UpdateWrapper<Posts>()
                        .eq("post_id", comment.getPostId())
                        .setSql("comment_count = comment_count - " + deletedCount)
        );
        //减少一级评论回复数
        if (comment.getParentId() != null && comment.getParentId() != 0) {
            commentsMapper.update(null,
                    new UpdateWrapper<Comments>()
                            .eq("comment_id", comment.getParentId())
                            .setSql("reply_count = reply_count - 1")
            );
        }
    }

    public IPage<CommentVO> getCommentsByPostId(Integer postId,Integer postAuthorId, int page, int pageSize) {
        Page<Comments> pageRequest = new Page<>(page, pageSize);

        // 1. 查询分页的一级评论（parent_id 为 null 或 0）
        IPage<Comments> rootPage = this.page(pageRequest,
                new QueryWrapper<Comments>()
                        .eq("post_id", postId)
                        .and(qw -> qw.isNull("parent_id").or().eq("parent_id", 0))
                        .eq("status", 1)
                        .orderByAsc("created_at")
        );

        List<Comments> rootComments = rootPage.getRecords();
        if (rootComments.isEmpty()) {
            return new Page<>(page, pageSize); // 空页
        }

        // 2. 查询子评论：根据一级评论的 commentId 查询所有 root_id 为它们的评论
        List<Integer> rootIds = rootComments.stream()
                .map(Comments::getCommentId)
                .collect(Collectors.toList());

        List<Comments> childComments = this.list(
                new QueryWrapper<Comments>()
                        .eq("post_id", postId)
                        .in("root_id", rootIds)
                        .eq("status", 1)
                        .orderByAsc("created_at")
        );

        // 3. 收集 parent 评论 ID（即被回复对象）
        Set<Integer> parentCommentIds = childComments.stream()
                .map(Comments::getParentId)
                .filter(pid -> pid != null && pid != 0)
                .collect(Collectors.toSet());

        Map<Integer, Comments> parentCommentMap;
        if (!parentCommentIds.isEmpty()) {
            List<Comments> parentComments = this.list(
                    new QueryWrapper<Comments>().in("comment_id", parentCommentIds)
            );
            parentCommentMap = parentComments.stream()
                    .collect(Collectors.toMap(Comments::getCommentId, Function.identity()));
        } else {
            parentCommentMap = new HashMap<>();
        }

        // 4. 查出所有涉及的用户（发评论的 + 被回复的）
        Set<Integer> userIds = Stream.concat(
                        Stream.concat(rootComments.stream(), childComments.stream()),
                        parentCommentMap.values().stream()
                )
                .map(Comments::getUserId)
                .collect(Collectors.toSet());

        Map<Integer, AuthorVO> authorMap = usersMapper.selectBatchIds(userIds).stream()
                .collect(Collectors.toMap(
                        Users::getUserId,
                        user -> {
                            AuthorVO authorVO = new AuthorVO();
                            authorVO.setId(user.getUserId());
                            authorVO.setName(user.getUsername());
                            authorVO.setImg(user.getAvatar());
                            authorVO.setIsAuthor(user.getUserId().equals(postAuthorId));
                            return authorVO;
                        }
                ));

        // 5. 构建子评论列表映射（按 root_id 分组）
        Map<Integer, List<CommentVO>> childrenMap = childComments.stream()
                .map(c -> convertToVO(c, authorMap, parentCommentMap))
                .collect(Collectors.groupingBy(CommentVO::getRootId));

        // 6. 构建一级评论 + 子评论结构
        List<CommentVO> commentVOs = rootComments.stream()
                .map(c -> {
                    CommentVO vo = convertToVO(c, authorMap, parentCommentMap);
                    vo.setReply(childrenMap.getOrDefault(c.getCommentId(), new ArrayList<>()));
                    return vo;
                }).collect(Collectors.toList());

        // 7. 封装分页结果
        Page<CommentVO> voPage = new Page<>();
        voPage.setCurrent(rootPage.getCurrent());
        voPage.setSize(rootPage.getSize());
        voPage.setTotal(rootPage.getTotal());
        voPage.setPages(rootPage.getPages());
        voPage.setRecords(commentVOs);

        return voPage;
    }

    private CommentVO convertToVO(Comments comment, Map<Integer, AuthorVO> authorMap,
                                  Map<Integer, Comments> parentCommentMap) {
        CommentVO vo = new CommentVO();
        vo.setId(comment.getCommentId());
        vo.setContent(comment.getContent());
        int likeCount = userLikesServiceImpl.getLikeCount(comment.getCommentId(), 1);
        if(likeCount<0) likeCount=0;
        vo.setLike(likeCount);
        vo.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(comment.getCreatedAt()));
        vo.setIsLike(userLikesServiceImpl.getIsLike(comment.getCommentId(), 1));
        vo.setAuthor(authorMap.get(comment.getUserId()));
        vo.setParentId(comment.getParentId());
        vo.setRootId(comment.getRootId());
        vo.setImageUrl(comment.getImageUrl());
        // 设置 parentName（被回复人）
        if (comment.getParentId() != null && comment.getParentId() != 0) {
            Comments parent = parentCommentMap.get(comment.getParentId());
            if (parent != null) {
                AuthorVO parentAuthor = authorMap.get(parent.getUserId());
                if (parentAuthor != null) {
                    vo.setParentName(parentAuthor.getName());
                }
            }
        }
        //vo.setIsLike(userLikesServiceImpl.getIsLike(comment.getCommentId(),1));
        return vo;
    }

    public void removeCommentsByPostId(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("帖子ID不能为空");
        }
        // 删除所有与该帖子相关的评论
        commentsMapper.delete(new QueryWrapper<Comments>().eq("post_id", id));
    }
}
